from flask import Blueprint, jsonify, request
from app.models.llm_agent import LLMAgent
from loguru import logger

llm_bp = Blueprint('llm', __name__, url_prefix='/api/llm')


def init_llm_api(llm_agent: LLMAgent):
    """初始化LLM API"""

    @llm_bp.route('/run', methods=['POST'])
    def run_agent():
        logger.info("############## 开始处理LLM API请求 ############")
        logger.info(f"请求方法: {request.method}, 请求路径: {request.path}")
        logger.info(f"请求数据: {request.get_json()}")
        """运行代理处理查询"""
        data = request.get_json()
        query = data.get('query')

        if not query:
            logger.error("查询内容不能为空")
            return jsonify({"status": "error", "message": "查询内容不能为空"}), 400

        try:
            result = llm_agent.run(query)
            logger.info(f"############## 查询LLM问题：{query} ############")
            logger.info(f"############## 模型代理回答完毕，结果{result} ############")
            logger.info("############## 完成处理LLM API请求 ############")
            return jsonify({"status": "success", **result}), 200
        except Exception as e:
            logger.error(f"运行代理失败: {e}")
            logger.info("############## 处理LLM API请求失败 ############")
            return jsonify({"status": "error", "message": str(e)}), 500

    return llm_bp